<!--
 * @Descripttion:
 * @Author: liZhaoBo
 * @Date: 2024-02-22 13:38:10
 * @LastEditors: liZhaoBo
 * @LastEditTime: 2024-05-08 15:06:15
-->
<template>
  <a-button type="primary" @click="importView">导入</a-button>
  <!-- 批量导入对话框 -->
  <a-modal
    v-if="visibleOpen"
    v-model:visible="visible"
    :title="'批量导入' + title"
    width="800px"
    title-align="start"
    align-center
    render-to-body
    :mask-closable="false"
    class="batch-import-dialog"
    @close="closed"
  >
    <div class="steptabs">
      <a-tabs v-model:active-key="tabsActive" trigger="click">
        <a-tab-pane key="1" title="需求导入"></a-tab-pane>
        <a-tab-pane key="2" title="导入日志"></a-tab-pane>
      </a-tabs>
    </div>
    <div v-show="tabsActive === '1'" class="tabsone">
      <div class="steptop">
        <a-steps :current="stepActive">
          <a-step>上传文件</a-step>
          <a-step>核对数据</a-step>
          <a-step>导入数据</a-step>
        </a-steps>
      </div>
      <!-- 密级 -->
      <div v-show="stepActive === 1" class="secret-level-ara">
        <a-form
          ref="secretFormRef"
          :rules="rulesChild"
          :disabled="false"
          label-align="left"
          :model="secretForm"
          style="margin-top: 20px"
        >
          <a-form-item
            v-show="isSecretLevel"
            :label="'数据密级'"
            field="secretLevel"
            style="width: 50%"
          >
            <secret-level-select
              v-model="secretForm.secretLevel"
              :default-value="secretForm.secretLevel"
              style="width: 100%"
            />
          </a-form-item>
          <slot name="moreList" />
        </a-form>
      </div>
      <!-- 校验中 -->
      <div v-if="stepActive === 2 && importLoading" class="import-result-ara">
        <img src="@/assets/importModel/importing.svg" alt="" />
        <div class="import-result-title">
          <span>数据校验中，请稍后...</span>
        </div>
      </div>
      <!-- 校验数据为空 -->
      <div
        v-if="
          stepActive === 2 &&
          (checkFlg === '2' || checkFlg === '3') &&
          !importLoading
        "
        class="import-result-ara"
      >
        <img src="@/assets/importModel/importError.svg" alt="" />
        <div class="import-result-title">
          <span>{{ checkTitle }}</span>
        </div>
      </div>
      <!-- 校验成功 -->
      <div
        v-if="stepActive === 2 && checkFlg === '1' && !importLoading"
        class="check-success"
      >
        <i class="el-icon-success" />
        <span>校验成功，可以导入！</span>
      </div>
      <!-- 文件区域 -->
      <div
        v-if="
          stepActive === 1 ||
          (stepActive === 2 && checkFlg === '1' && !importLoading)
        "
        class="upload-ara"
      >
        <img
          v-if="fileList.length > 0"
          src="@/assets/importModel/xls.svg"
          style="width: 48px; height: 48px; margin-bottom: 8px"
          alt=""
        />
        <img
          v-else
          src="@/assets/importModel/waitFile.svg"
          style="width: 48px; height: 48px; margin-bottom: 8px"
          alt=""
        />
        <div v-for="item in fileList" :key="item.id" class="file-name">
          {{ item.name }}
        </div>
        <a-upload
          v-show="stepActive === 1"
          ref="uploadRef"
          v-model:file-list="fileList"
          class="upload-class"
          :headers="upload.headers"
          action="/"
          :disabled="upload.isUploading"
          :auto-upload="false"
          :accept="accept"
          :show-file-list="false"
          @change="handleChange"
        >
          <template #upload-button>
            <a-button v-if="fileList.length === 0">上传文件</a-button>
            <a-button v-else>重新上传</a-button>
          </template>
        </a-upload>
        <div v-if="fileList.length === 0" class="upload-tip">
          支持xlsx和xls文件
        </div>
      </div>
      <!-- 校验失败 -->
      <div
        v-if="stepActive === 2 && checkFlg === '0' && !importLoading"
        class="check-error"
      >
        <div class="check-error-tip">
          <div class="check-error-tip1">
            <i class="el-icon-warning" />
            <span v-if="checkSucNum === 0">全部校验失败，请检查后重新上传</span>
            <span v-else>部分校验失败</span>
          </div>
          <div class="check-error-tip2">
            有
            <span style="color: #d40000">{{ checkErrNum }}</span>
            条数据校验失败，
            <span style="color: #07bb06">{{ checkSucNum }}</span> 条数据校验成功
          </div>
        </div>
        <div class="check-error-title">
          以下为校验失败的数据列表，可
          <span style="color: #1e89ff; cursor: pointer" @click="dowCheckErrFile"
            >下载失败文件</span
          >
          ，修改后重新导入
        </div>
        <div class="checkErrorTable">
          <!-- <table-form
          ref="table1"
          border
          :columns="columns"
          :data="checkErrList"
          :action-option="{}"
          :disabled="true"
          style="width: 100%"
        >
        </table-form> -->
        </div>
      </div>
      <!-- 导入 -->
      <div v-if="stepActive === 3" class="import-result-ara">
        <img
          v-if="importLoading"
          src="@/assets/importModel/importing.svg"
          alt=""
        />
        <img
          v-if="!importLoading && importResult === 'success'"
          src="@/assets/importModel/importSuccess.svg"
          alt=""
        />
        <img
          v-if="!importLoading && importResult === 'error'"
          src="@/assets/importModel/importError.svg"
          alt=""
        />
        <div class="import-result-title">
          <span v-if="importLoading">导入中，请稍后...</span>
          <span v-if="!importLoading && importResult === 'success'"
            >导入成功</span
          >
          <span v-if="!importLoading && importResult === 'error'"
            >导入失败</span
          >
        </div>
        <div
          v-if="!importLoading && importResult === 'success'"
          class="import-result-tip"
        >
          <span
            >成功导入
            <span style="color: #07bb06">{{ resultSuccess }}</span>
            条数据，所有数据均可在
            <span style="color: #1e89ff; cursor: pointer" @click="finish"
              >父列表链接</span
            >
            中查看;</span
          >
          <span style="margin-top: 4px"
            >重复数据
            <span style="color: #d40000">{{ resultRepeat }}</span>
            条未导入;</span
          >
          <span style="margin-top: 4px"
            >失败数据
            <span style="color: #d40000">{{ resultError }}</span> 条未导入，请
            <span
              style="color: #1e89ff; cursor: pointer"
              @click="exportErrResult"
              >导出失败结果文件</span
            >
            ，重新上传失败数据;</span
          >
        </div>
      </div>
      <!-- 提示 -->
      <div v-if="stepActive === 1" class="tip">
        <div class="tip1">温馨提示：</div>
        <div class="tip2">
          <span style="margin-bottom: 5px"
            >1. 下载
            <span class="tip-dowload" @click="download">导入模版</span>
            ，编辑后导入</span
          >
          <span>2. 请将文件置于第一个sheet，文件不支持多行表头</span>
        </div>
      </div>
    </div>
    <div v-show="tabsActive === '2'" class="tabstwo">
      <mytable></mytable>
    </div>

    <template #footer>
      <a-button
        v-show="stepActive === 1 || tabsActive === '2'"
        @click="closed"
        >{{ '取消' }}</a-button
      >
      <a-button
        v-show="stepActive === 1 && tabsActive === '1'"
        type="primary"
        :disabled="fileList.length === 0"
        @click="checkData()"
        >{{ '核对数据' }}</a-button
      >
      <a-button
        v-show="stepActive === 2 && tabsActive === '1'"
        :disabled="importLoading"
        @click="preStep()"
        >{{ '上一步' }}</a-button
      >
      <a-button
        v-show="stepActive === 2 && tabsActive === '1'"
        type="primary"
        :disabled="
          importLoading ||
          checkFlg === '2' ||
          checkFlg === '3' ||
          (checkFlg === '0' && checkSucNum === 0)
        "
        @click="importData()"
        >{{ '导入' }}</a-button
      >
      <a-button
        v-show="stepActive === 3 && tabsActive === '1'"
        :disabled="importLoading"
        @click="continueUpload()"
        >{{ '继续上传' }}</a-button
      >
      <a-button
        v-show="stepActive === 3 && tabsActive === '1'"
        type="primary"
        :disabled="importLoading"
        @click="finish()"
        >{{ '完成' }}</a-button
      >
    </template>
  </a-modal>
</template>

<script setup lang="ts">
  import axios from 'axios';
  import { FileItem, Message } from '@arco-design/web-vue';
  import secretLevelSelect from '@/common/components/cac-components/secret-level-select/index.vue';
  import { getToken } from '@/utils/auth';
  import { ref, defineProps, onMounted, defineEmits } from 'vue';
  import mytable from './table.vue';

  const importView = () => {
    visibleOpen.value = true;
  };
  const emit = defineEmits(['closeDrawer', 'finish']);
  const props = defineProps({
    title: {
      type: String,
      default: '',
    },
    // 下载模板
    exportUrl: {
      type: [String, Array],
      default: '',
      required: false,
    },
    checkUrl: {
      type: String,
      default: '',
    },
    // 导入
    importUrl: {
      type: String,
      default: '',
    },
    accept: {
      type: String,
      default: '.xlsx, .xls',
      required: false,
    },
    cols: {
      type: Array,
      default: null,
    },
    params: {
      type: Object,
      default: () => {
        return {};
      },
      required: false,
    },
    isShowDownLoad: {
      type: Boolean,
      default: true,
    },
  });
  const tabsActive = ref('1');
  const secretFormRef = ref();
  const secretForm = ref({
    secretLevel: '',
  });
  const importLoading = ref<boolean>(false);
  const importResult = ref<any>([]);
  const checkErrList = ref<any>([]);
  const columns = ref<any>([]);
  const checkErrId = ref('');
  const checkErrNum = ref<number>(0);
  const checkSucNum = ref<number>(0);
  // 校验结果 0：部分校验失败，1：校验成功，2：模板数据为空，3：其他
  const checkFlg = ref<string>('1');
  const checkTitle = ref<string>('');
  const stepActive = ref<number>(1);
  const resultSuccess = ref<number>(0);
  const resultRepeat = ref<number>(0);
  const resultError = ref<number>(0);
  const resultData = ref<any>([]);
  const importantLoading = ref(false);
  const isSecretLevel = ref(true);
  const visible = ref(true);
  const visibleOpen = ref(false);
  const rulesChild = ref({
    secretLevel: [
      {
        required: true,
        message: '请选择',
        trigger: ['blur', 'change'],
      },
    ],
  });
  const fileList = ref<any[]>([]);
  const uploadRef = ref();
  const upload = ref({
    // 是否禁用上传
    isUploading: false,
    // 设置上传的请求头部
    headers: {
      Authorization: `Bearer ${getToken()}`,
    },
  });
  onMounted(() => {
    console.log('1111');
  });
  const closed = () => {
    stepActive.value = 1;
    tabsActive.value = '1';
    secretFormRef.value.resetFields();
    secretFormRef.value.clearValidate();
    visibleOpen.value = false;
    fileList.value = [];
    emit('closeDrawer');
  };
  // 校验数据
  const checkData = () => {
    if (isSecretLevel.value) {
      secretFormRef.value.validate().then(() => {
        checkDataResult();
      });
    } else {
      checkDataResult();
    }
  };
  const checkDataResult = () => {
    stepActive.value = 2;
    importLoading.value = true;
    const formData = new FormData();
    formData.append('file', fileList.value[0].raw); // file文件
    // axios({
    //   url: `/api${props.checkUrl}`,
    //   method: 'post',
    //   data: formData,
    //   headers: {
    //     Authorization: `Bearer ${getToken()}`,
    //   },
    // })
    //   .then((res) => {
    //     console.log('res---------', res);
    //     importLoading.value = false;
    //     if (res.data.code === 200) {
    //       checkFlg.value = '1';
    //       checkErrNum.value = res.data.data.failNum;
    //       checkSucNum.value = res.data.data.successNum;
    //       checkErrId.value = res.data.data.errorInfoFileId;

    //       if (checkErrNum.value > 0) {
    //         checkFlg.value = '0';
    //         columns.value = [...props.cols];
    //         checkErrList.value = res.data.data.errorList.slice(1, 6);
    //       }
    //     } else if (res.data.msg === '导入数据为空!') {
    //       checkFlg.value = '2';
    //       checkTitle.value = '模板为空，请检查后重新上传';
    //     } else {
    //       checkFlg.value = '3';
    //       checkTitle.value = res.data.msg;
    //     }
    //   })
    //   .catch(() => {
    //     importLoading.value = false;
    //     checkFlg.value = '3';
    //     checkTitle.value = '接口出现错误';
    //   });
    getTestData();
  };
  const getTestData = () => {
    importResult.value = 'success';
    resultSuccess.value = 3;
    resultRepeat.value = 4;
    resultError.value = 5;
    checkFlg.value = '1';
    checkErrNum.value = 3;
    checkSucNum.value = 4;
    checkErrId.value = '1111111';
    importLoading.value = false;
    if (checkErrNum.value > 0) {
      checkFlg.value = '0';
      columns.value = [...props.cols];
      checkErrList.value = [
        {
          id: '111',
        },
        {
          id: '2222',
        },
      ];
    }
  };
  // 上一步
  const preStep = () => {
    stepActive.value = 1;
  };
  // 下载check错误文件
  const dowCheckErrFile = () => {
    const url = `/file/info/download/${checkErrId.value}`;
    handleDownload(url, 'GET', `${props.title}（校验失败）`);
  };
  // 导出失败结果文件
  const exportErrResult = () => {
    dowCheckErrFile();
  };
  // 导入
  const importData = () => {
    stepActive.value = 3;
    importLoading.value = true;
    const formData = new FormData();
    formData.append('file', fileList.value[0].raw); // file文件
    // axios({
    //   url: `/api${props.importUrl}&secretLevel=${secretForm.value.secretLevel}`,
    //   method: 'post',
    //   data: formData,
    //   headers: {
    //     Authorization: `Bearer ${getToken()}`,
    //   },
    // })
    //   .then((res) => {
    //     importLoading.value = false;
    //     if (res.data.code === 200) {
    //       importResult.value = 'success';
    //       resultSuccess.value = res.data.data.successNum;
    //       resultRepeat.value = res.data.data.repeatNum;
    //       resultError.value = res.data.data.failNum;
    //     } else {
    //       importResult.value = 'error';
    //     }
    //   })
    //   .catch(() => {
    //     importLoading.value = false;
    //     importResult.value = 'error';
    //   });
    getTestData();
  };
  // 继续上传
  const continueUpload = () => {
    stepActive.value = 1;
    fileList.value = [];
  };
  // 完成
  const finish = () => {
    const response = {
      code: 200,
      data: resultData.value,
    };
    if (importResult.value === 'success') {
      emit('finish', response, secretForm.value.secretLevel);
      closed();
    } else {
      closed();
    }
  };
  // 下载文件
  const downBlob = (res: any, fileNameDown: any) => {
    const blob = res.data;
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onload = (e) => {
      const a = document.createElement('a');
      a.download = fileNameDown;
      a.href = e.target.result;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    };
  };
  const download = () => {
    if (typeof props.exportUrl === 'string') {
      handleDownload(props.exportUrl, 'post', `${props.title}模板`);
    } else {
      props.exportUrl.forEach((item: any) => {
        handleDownload(item.url, 'post', props.title + item.name);
      });
    }
  };
  const handleDownload = (
    url: string,
    method: string,
    name: string,
    par = {}
  ) => {
    const dParams = { ...par, ...props.params };
    importantLoading.value = true;
    axios({
      url: `/api${url}`,
      method,
      responseType: 'blob',
      params: dParams,
      headers: { Authorization: `Bearer ${getToken()}` },
    })
      .then((res) => {
        if (res.data.type === 'application/json') {
          const reader: any = new FileReader();
          reader.onload = () => {
            const messageObj = JSON.parse(reader.result);
            Message.error(messageObj.msg);
          };
          reader.readAsText(res.data, 'utf-8');
        } else {
          downBlob(res, `${name}.xls`);
          Message.success('导出成功');
        }
        importantLoading.value = false;
      })
      .catch(() => {
        Message.error('导出失败');
        importantLoading.value = false;
      });
  };
  const handleChange = (fileList1: FileItem[]) => {
    if (fileList1.length > 1) {
      fileList.value = fileList1.splice(1, 1);
    } else {
      fileList.value = fileList1;
    }
  };
</script>

<style lang="less">
  .batch-import-dialog {
    .arco-modal-header {
      padding: 12px 24px 4px;
      color: #1e2228;
      border-bottom: none !important;
    }

    .arco-modal-body {
      padding: 0 0 24px !important;

      .steptabs {
        .arco-tabs-nav-type-line .arco-tabs-tab {
          padding: 12px 16px;
        }

        .arco-tabs-content {
          display: none;
        }
      }

      .tabsone {
        padding: 24px 24px 0;

        .steptop {
          margin-bottom: 24px;
          padding: 0 120px 0 77px;
        }

        .secret-level-ara {
          margin-bottom: 20px;
          padding: 16px 20px;
          background: #f7f9fc;
          border-radius: 6px;

          .arco-form {
            margin-top: 0 !important;

            .arco-row {
              display: flex;
              flex-direction: column;
              margin-bottom: 4px;

              .arco-form-item-label-col {
                width: 50% !important;
              }

              .arco-select-view-single {
                background-color: #fff !important;
                border: 1px solid #cad0db;
                border-radius: 4px;
              }
            }
          }
        }

        .check-success {
          display: flex;
          align-items: center;
          height: 64px;
          margin-bottom: 20px;
          padding-left: 30px;
          color: #1e2228;
          font-size: 16px;
          background: #ecffe8;
          border: 1px solid #89e47f;
          border-radius: 8px;

          i {
            margin-right: 20px;
            color: #07bb06;
            font-size: 21px;
          }
        }

        .check-error {
          .check-error-tip {
            display: flex;
            flex-direction: column;
            justify-content: center;
            height: 90px;
            margin-bottom: 20px;
            padding-left: 30px;
            color: #1e2228;
            font-size: 16px;
            background: #fffae8;
            border: 1px solid #ffdc8c;
            border-radius: 8px;

            .check-error-tip1 {
              display: flex;
              align-items: center;
              height: 24px;
              margin-bottom: 4px;
              line-height: 24px;

              i {
                margin-right: 20px;
                color: #ff9a01;
                font-size: 21px;
              }
            }

            .check-error-tip2 {
              height: 22px;
              padding-left: 41px;
              font-size: 14px;
              line-height: 22px;
            }
          }

          .check-error-title {
            height: 22px;
            margin: 20px 0;
            line-height: 22px;
          }
        }

        .upload-ara {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding: 24px 0;
          background: #f7f9fc;
          border: 1px dashed #cad0db;
          border-radius: 6px;

          .file-name {
            height: 24px;
            margin-bottom: 8px;
            font-size: 16px;
            line-height: 24px;
          }

          .upload-tip {
            height: 22px;
            margin-top: 8px;
            color: #828b9b;
            line-height: 22px;
            text-align: center;
          }
        }

        .import-result-ara {
          display: flex;
          flex-direction: column;
          align-items: center;

          img {
            width: 360px;
            height: 240px;
          }

          .import-result-title {
            margin-top: 20px;
            font-size: 16px;
          }

          .import-result-tip {
            display: flex;
            flex-direction: column;
            width: calc(100% - 48px);
            margin-top: 20px;
            padding: 24px;
            background: #f7f8fa;

            span {
              display: inline-block;
              height: 22px;
              line-height: 22px;
            }
          }
        }

        .tip {
          color: #828b9b;

          .tip1 {
            height: 22px;
            margin: 16px 0 8px;
            line-height: 22px;
          }

          .tip2 {
            display: flex;
            flex-direction: column;

            .tip-dowload {
              color: #1e89ff;
              cursor: pointer;
            }
          }
        }
      }

      .tabstwo {
        min-height: 400px;
        padding: 24px 24px 0;
      }
    }

    ::v-deep .arco-modal-footer {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      height: 52px;
      padding: 0 24px !important;
      border-top: 1px solid #e4e7ed;
      box-shadow: none !important;
    }
  }
</style>
